#include <graphics/vertexarray.h>
#include <graphics/utils.h>
#include <QtOpenGL/qglshaderprogram.h>
#include <assert.h>

namespace yam3d
{
namespace graphics
{

class VertexArrayImpl
{
public:
    virtual void setAttributeArray(QGLShaderProgram* program, const char* const name, int stride) = 0;
};

template <class DataType>
class VertexArrayImplTemplate : public VertexArrayImpl
{
public:
    VertexArrayImplTemplate<DataType>( const core::vector<DataType>& data )
        : VertexArrayImpl()
        , m_data(data)
    {
    }

    virtual ~VertexArrayImplTemplate<DataType>()
    {
    }

    virtual void setAttributeArray(QGLShaderProgram* program, const char* const name, int stride)
    {
        program->setAttributeArray( name, m_data.constData(), sizeof(DataType) );
        checkGlError("QGLShaderProgram::setAttributeArray(name=%s, data, stride=%d)", name, sizeof(DataType) );
    }

private:
    QVector<DataType> m_data;
};

VertexArray::VertexArray( const core::vector<math::vec4>& data )
{
    m_impl = new VertexArrayImplTemplate<math::vec4>(data);
}

VertexArray::VertexArray( const core::vector<math::vec3>& data )
{
    m_impl = new VertexArrayImplTemplate<math::vec3>(data);
}

VertexArray::VertexArray( const core::vector<math::vec2>& data )
{
    m_impl = new VertexArrayImplTemplate<math::vec2>(data);
}

VertexArray::VertexArray( const core::vector<float>& data )
{
    m_impl = new VertexArrayImplTemplate<float>(data);
}

VertexArray::~VertexArray()
{
    SAFE_DELETE(m_impl);
}


void VertexArray::setAttributeArray(QGLShaderProgram* program, const char* const name, int stride)
{
    assert(m_impl != 0);
    m_impl->setAttributeArray(program, name, stride);
}


}
}

